var express = require("express");
var router = express.Router();
var Article = require("../../models/admin/article.js");
var Article = new Article();
router.post("/addArticle" , function(req , res){
  var body = req.body;
  var data = {
    id:body._id,
    title:body.title,
    column:body.column,
    author:body.author || "小缘",
    releaseTime:new Date().getTime(),
    briefing:body.briefing,
    source:body.source,
    content:body.content
  };
  if(!data.title){
    return res.json({
      state:"error",
      message:"请输入标题"
    });
  };
  if(!data.column){
    return res.json({
      state:"error",
      message:"请选择栏目"
    })
  };
  if(!data.briefing){
    return res.json({
      state:"error",
      message:"请输入简介"
    })
  };
  if(!data.content){
    return res.json({
      state:"error",
      message:"请输入文章内容"
    })
  };
  //调用保存
  if(data.id){
    Article.editArticle(data , function(error , data){
      if(error){
        return res.json({
          state:"error",
          message:"保存失败"
        });
      }else{
        return res.json({
          state:"ok",
          message:"编辑成功"
        });
      };
    });
  }else{
    Article.addArticle(data , function(error , data){
      if(error){
        return res.json({
          state:"error",
          message:"操作失败"
        });
      }else{
        return res.json({
          state:"ok",
          message:"发布成功"
        });
      };
    });
  };
});
//获取
router.post("/getArticle" , function(req , res){
  var data = req.body;
  Article.get(data , function(error , data){
    if(error){
      return res.json({
        state:"error",
        message:error
      });
    }else{
      return res.json({
        state:"ok",
        message:"",
        article:data
      });
    }
  })
});
//文章详情
router.get("/articleDetails" , function(req , res){
  var data = {
    _id:req.query.id
  };
  if(!data._id){
    return res.json({
      state:"error",
      message:"文章id不能为空"
    });
  };
  Article.getOne(data , function(error , data){
    if(error){
      return res.json({
        state:"error",
        message:error
      });
    }else{
      return res.json({
        state:"ok",
        message:"",
        article:data
      });
    };
  });
});
//删除
router.post("/delArticle" , function(req , res){
  var id = req.body.id;
  if(!id){
    return res.json({
      state:"error",
      message:"请选择要删除的文章"
    });
  }else{
    Article.del({_id:id} , function(error , data){
      if(error){
        return res.json({
          state:"error",
          message:error
        });
      }else{
        return res.json({
          state:"ok",
          message:"删除成功"
        });
      };
    });
  };
});
module.exports = router;
